﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace DomainInfoLib
{
    public class WhomsyAPI:IWebAPI
    {
        private static bool? ProcessAvaliableStr(string avaliableStr)
        {
            if (string.IsNullOrEmpty(avaliableStr))
            {
                return null;
            }

            int pos = avaliableStr.IndexOf("information");

            if (pos==-1)
            {
                return null;
            }

            string key = avaliableStr.Substring(pos+14,2);

            if (key == "No")
            {
                return true;
            }

            return false;
        }


        private static string ProcessXmlStr(string XmlStr)
        {
            try
            {
                if (string.IsNullOrEmpty(XmlStr)) return "";

                XmlDocument xdoc = new XmlDocument();

                xdoc.LoadXml(XmlStr);

                XmlNode xn = xdoc.ChildNodes[1].ChildNodes[1];

                return xn.InnerText;
            }
            catch(XmlException ex)
            {

                return XmlStr;
            }



        }

        public string GetUrl(string DomainName)
        {
            string url = string.Format("http://whomsy.com/api/{0}?output=xml", DomainName);

            return url;
        }

        public RegisterInfo GetResponseByWebAPI(string DomainName)
        {

            string url = GetUrl(DomainName);

            string xmlstr = BaseInfo.CallWebPage(url, null, Encoding.UTF8);

            string avaliableStr = ProcessXmlStr(xmlstr);

            bool? Avaliable = ProcessAvaliableStr(avaliableStr);

            if (!Avaliable.HasValue)
            {
                return null;
            }

            return RegisterInfo.BuildRegisterInfo(DomainName, xmlstr, Avaliable, this.GetType().Name);
        }
    }
}
